from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from apps.oauth.contants import OPENID_TOKEN_EXPIRES_TIME
from meiduo import settings
import logging

logger = logging.getLogger('django')

def generic_openid_token(openid):
    # 创建实例对象
    # s = Serializer(secret_key=settings.SECRET_KEY,expires_in=300)
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=OPENID_TOKEN_EXPIRES_TIME)

    # 组织数据
    data = {
        'openid' : openid
    }

    # 加密数据
    token = s.dumps(data)
    # 返回数据
    return token.decode()

from itsdangerous import SignatureExpired,BadData
def check_openid_tocken(token):
    # 创建实例
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=OPENID_TOKEN_EXPIRES_TIME)


    # 解密 解密的时候需要捕获异常
    try:

        request = s.loads(token)
    # except Exception as e:
    #     return None
    except SignatureExpired as e:
        logger.error(e)
        return None

    return request.get('openid')
    # 获取解密后的数据

